package com.ly.erms.common.constant.factory;

import java.util.ArrayList;
import java.util.List;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ly.erms.common.constant.cache.Cache;
import com.ly.erms.common.constant.cache.CacheKey;
import com.ly.erms.common.constant.state.ManagerStatus;
import com.ly.erms.common.constant.state.MenuStatus;
import com.ly.erms.common.persistence.dao.BaseconfigClassificationMapper;
import com.ly.erms.common.persistence.dao.DeptMapper;
import com.ly.erms.common.persistence.dao.DictMapper;
import com.ly.erms.common.persistence.dao.MenuMapper;
import com.ly.erms.common.persistence.dao.RoleMapper;
import com.ly.erms.common.persistence.dao.UserMapper;
import com.ly.erms.common.persistence.model.BaseconfigClassification;
import com.ly.erms.common.persistence.model.Dept;
import com.ly.erms.common.persistence.model.Dict;
import com.ly.erms.common.persistence.model.Menu;
import com.ly.erms.common.persistence.model.Role;
import com.ly.erms.common.persistence.model.User;
import com.ly.erms.core.log.LogObjectHolder;
import com.ly.erms.core.support.StrKit;
import com.ly.erms.core.util.Convert;
import com.ly.erms.core.util.SpringContextHolder;
import com.ly.erms.core.util.ToolUtil;

@Component
@DependsOn("springContextHolder")
public class ConstantFactory implements IConstantFactory {
	private RoleMapper roleMapper = SpringContextHolder.getBean(RoleMapper.class);
	private DeptMapper deptMapper = SpringContextHolder.getBean(DeptMapper.class);
	private DictMapper dictMapper = SpringContextHolder.getBean(DictMapper.class);
	private UserMapper userMapper = SpringContextHolder.getBean(UserMapper.class);
	private MenuMapper menuMapper = SpringContextHolder.getBean(MenuMapper.class);
	private BaseconfigClassificationMapper classificationMapper = SpringContextHolder
			.getBean(BaseconfigClassificationMapper.class);

	public static IConstantFactory me() {
		return SpringContextHolder.getBean("constantFactory");
	}

	@Override
	public String getUserNameById(Integer userId) {
		User user = userMapper.selectById(userId);
		if (user != null) {
			return user.getName();
		} else {
			return "--";
		}
	}

	@Override
	public String getUserAccountById(Integer userId) {
		User user = userMapper.selectById(userId);
		if (user != null) {
			return user.getAccount();
		} else {
			return "--";
		}
	}

	@Override
	//@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.ROLE_NAME + "'+#roleIds")
	public String getRoleName(String roleIds) {
		Integer[] roles = Convert.toIntArray(roleIds);
		StringBuilder sb = new StringBuilder();
		for (Integer role : roles) {
			Role roleObj = roleMapper.selectById(role);
			if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getName())) {
				sb.append(roleObj.getName()).append(",");
			}
		}
		return StrKit.removeSuffix(sb.toString(), ",");
	}

	@Override
//	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_NAME + "'+#roleId")
	public String getSingleRoleName(Integer roleId) {
		if (0 == roleId) {
			return "--";
		}
		Role roleObj = roleMapper.selectById(roleId);
		if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getName())) {
			return roleObj.getName();
		}
		return "";
	}

	@Override
//	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_TIP + "'+#roleId")
	public String getSingleRoleTip(Integer roleId) {
		if (0 == roleId) {
			return "--";
		}
		Role roleObj = roleMapper.selectById(roleId);
		if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getTips())) {
			return roleObj.getTips();
		}
		return "";
	}

	@Override
//	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.DEPT_NAME + "'+#deptId")
	public String getDeptName(Integer deptId) {
		Dept dept = deptMapper.selectById(deptId);
		if (ToolUtil.isNotEmpty(dept) && ToolUtil.isNotEmpty(dept.getFullname())) {
			return dept.getFullname();
		}
		return "";
	}

	@Override
//	@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.CLASSIFICATION_NAME + "'+#id")
	public String getClassificationName(Integer id) {
		BaseconfigClassification classification = classificationMapper.selectById(id);
		if (ToolUtil.isEmpty(classification)) {
			return id==0?"顶级":"";
		} else {
			return classification.getClassname();
		}
	}

	@Override
	public String getMenuNames(String menuIds) {
		Integer[] menus = Convert.toIntArray(menuIds);
		StringBuilder sb = new StringBuilder();
		for (int menu : menus) {
			Menu menuObj = menuMapper.selectById(menu);
			if (ToolUtil.isNotEmpty(menuObj) && ToolUtil.isNotEmpty(menuObj.getName())) {
				sb.append(menuObj.getName()).append(",");
			}
		}
		return StrKit.removeSuffix(sb.toString(), ",");
	}

	@Override
	public String getMenuName(Long menuId) {
		if (ToolUtil.isEmpty(menuId)) {
			return "";
		} else {
			Menu menu = menuMapper.selectById(menuId);
			if (menu == null) {
				return "";
			} else {
				return menu.getName();
			}
		}
	}

	@Override
	public String getMenuNameByCode(String code) {
		if (ToolUtil.isEmpty(code)) {
			return "";
		} else {
			Menu param = new Menu();
			param.setCode(code);
			Menu menu = menuMapper.selectOne(param);
			if (menu == null) {
				return "";
			} else {
				return menu.getName();
			}
		}
	}

	@Override
	public String getDictName(Integer dictId) {
		if (ToolUtil.isEmpty(dictId)) {
			return "";
		} else {
			Dict dict = dictMapper.selectById(dictId);
			if (dict == null) {
				return "";
			} else {
				return dict.getName();
			}
		}
	}

	@Override
	public String getNoticeTitle(Integer dictId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getDictsByName(String name, Integer val) {
		Dict temp = new Dict();
		temp.setName(name);
		Dict dict = dictMapper.selectOne(temp);
		if (dict == null) {
			return "";
		} else {
			Wrapper<Dict> wrapper = new EntityWrapper<>();
			wrapper = wrapper.eq("pid", dict.getId());
			List<Dict> dicts = dictMapper.selectList(wrapper);
			for (Dict item : dicts) {
				if (item.getNum() != null && item.getNum().equals(val)) {
					return item.getName();
				}
			}
			return "";
		}
	}

	@Override
	public String getSexName(Integer sex) {
		return getDictsByName("性别", sex);
	}

	@Override
	public String getStatusName(Integer status) {
		return ManagerStatus.valueOf(status);
	}

	@Override
	public String getMenuStatusName(Integer status) {
		return MenuStatus.valueOf(status);
	}

	@Override
	public List<Dict> findInDict(Integer id) {
		if (ToolUtil.isEmpty(id)) {
			return null;
		} else {
			EntityWrapper<Dict> wrapper = new EntityWrapper<Dict>();
			List<Dict> dicts = dictMapper.selectList(wrapper.eq("pid", id));
			if (dicts == null || dicts.size() == 0) {
				return null;
			} else {
				return dicts;
			}

		}
	}

	/**
	 * 获取被缓存的业务对象（用户删除业务）
	 */
	@Override
	public String getCacheObject(String para) {
		return LogObjectHolder.me().get().toString();
	}

	@Override
	public List<Integer> getSubDeptId(Integer deptid) {
		Wrapper<Dept> wrapper = new EntityWrapper<>();
		wrapper = wrapper.like("pids", "%[" + deptid + "]%");
		List<Dept> depts = this.deptMapper.selectList(wrapper);

		ArrayList<Integer> deptids = new ArrayList<>();

		if (depts != null && depts.size() > 0) {
			for (Dept dept : depts) {
				deptids.add(dept.getId());
			}
		}

		return deptids;
	}

	@Override
	public List<Integer> getParentDeptIds(Integer deptid) {
		Dept dept = deptMapper.selectById(deptid);
		String pids = dept.getPids();
		String[] split = pids.split(",");
		ArrayList<Integer> parentDeptIds = new ArrayList<>();
		for (String s : split) {
			parentDeptIds.add(Integer.valueOf(StrKit.removeSuffix(StrKit.removePrefix(s, "["), "]")));
		}
		return parentDeptIds;
	}

}
